package com.edou.member.controller.weixin;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.annotation.Resource;
import javax.mail.MessagingException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang3.StringUtils;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import com.edou.base.constant.SessionConstant;
import com.edou.base.controller.BaseController;
import com.edou.base.util.EncryptUtil;
import com.edou.base.util.UUIDUtil;
import com.edou.member.entity.MemberRole;
import com.edou.member.entity.MemberUser;
import com.edou.member.entity.MemberUserRole;
import com.edou.member.form.MemberUserForm;
import com.edou.member.service.IMemberRoleService;
import com.edou.member.service.IMemberUserRoleService;
import com.edou.member.service.IMemberUserService;
import com.edou.system.service.ISysMailService;

/**
 * 会员登录模块
 * @creator     admin
 * @create-time 2016/3/12 16:10:22
 * @email admin@edou.com
 * @company www.edou.com
 * @version 1.0
 */
@Controller("memberUserLoginWeixinController")
@Scope("prototype")
@RequestMapping("/weixin/member")
public class MemberUserLoginWeixinController extends BaseController {

	@Resource(name = "memberUserServiceImpl")
	private IMemberUserService memberUserService;
	
	@Resource
	private ISysMailService emailService;
	@Resource
	private IMemberUserRoleService memberUserRoleService;
	@Resource 
	private IMemberRoleService memberRoleService;
	
	/**
	 * 跳转到登录页
	 * @return 
	 */
	@RequestMapping(value = "/login.htm", method = RequestMethod.GET)
	public ModelAndView login(@ModelAttribute MemberUserForm model, HttpServletRequest request, HttpServletResponse response, HttpSession session){
		ModelAndView view = new ModelAndView();
		Map<String, Object> data = view.getModel();
		// 点击记住我--会员退出判断
		Integer  isRmbPwd = 0;
		// 处理---记住我
		Cookie cookies[] = request.getCookies();
		if (cookies != null) {
			for (Cookie cookie : cookies) {
				// 记住我
				if ("memberAutoLogin".equals(cookie.getName())) {
					String memberUUID = cookie.getValue();
					MemberUser member = (MemberUser)session.getAttribute(memberUUID);
					data.put("member",member);
					isRmbPwd = 1;
					data.put("isRmbPwd", isRmbPwd);
				}
			}
		}
		
		// 登录后跳转的页面
		String preUrl = model.getPreUrl();
		if(StringUtils.isNotBlank(preUrl)){
			session.setAttribute("preUrl",preUrl);
		}
		
		//转发到首页
		view.setViewName("/member/login/login");
		return view;
	}
	
	/**
	 * 跳转到登录页 - 弹出框中展示
	 * @return 
	 */
	@RequestMapping(value = "/login_pop.htm", method = RequestMethod.GET)
	public String loginInc(){
		return "/member/login/login_pop";
	}
	
	/**
	 * 执行登录：验证会员名和密码是否正确
	 * 
	 * 参数： memeber 会员实体 verCode 验证码  isRmbPwd 记住我
	 * 处理： 验证会员名和密码是否正确
	 *       
	 * @return json字符串 
	 * success - 正确，设置Session中的会员信息 
	 * error - 错误
	 */
	@RequestMapping(value = "/do_login.htm", method = RequestMethod.POST)
	public ModelAndView doLogin(@ModelAttribute MemberUserForm model, HttpServletRequest request, HttpServletResponse response, HttpSession session){
		try{
			/* ======= 1、验证验证码是否正确 ======= */
			Integer v = model.getV();
			if(v != null && v.intValue() == 1){
				// 获取客户端输入的验证码
				String verCode = model.getVerCode();
				// 获取服务器端正确的验证码
				String verCodeSession = (String)session.getAttribute(SessionConstant.JAPTCHACODE);
				if (StringUtils.isBlank(verCode) || !verCode.toLowerCase().equals(verCodeSession.toLowerCase())) {
					// 如果验证码为空，或者验证码不正确
					return ajaxJSON(Status.error, "验证码输入不正确");
				}
			}

			/* ======= 2、验证会员帐号密码是否正确 ======= */
			// 会员验证是否通过 true-通过 false-不通过
			boolean loginPass = false;
			MemberUser member = model.getItem();
			String account = member.getAccount();
			String password = member.getPassword();
			String passwordEncrypt = EncryptUtil.encryptionPw(password);
			
			// 验证用户名与密码是否正确
			MemberUser memberDb = memberUserService.getMemberUserByAccountAndPassword(account, passwordEncrypt);
			if(null != memberDb){
				loginPass = true;
			}
			
			if(loginPass){
				// 会员的启用状态
				if(memberDb.getState() != null && memberDb.getState() == 1){
					return ajaxJSON(Status.error,"该账户已被禁用");
				}
				
				//处理记住我
				Integer isRmbPwd = model.getIsAutoLogin();
				if(null != isRmbPwd && isRmbPwd.intValue() == 1){
					//随机生成ID
					String memberUUID = UUIDUtil.uuid();
					//存入Cookie  通过UUID标记会员ID
					setCookie("memberAutoLogin", memberUUID, 7 * 24 * 60 * 60, request, response);
					// 此处为了记住密码，需要将加密前的密码返还到登录页中
					MemberUser memberLogin = memberDb;
					memberLogin.setPassword(password);
					session.setAttribute(memberUUID, memberLogin);
				}else{
					removeCookie("memberAutoLogin",request,response);
				}
				
				// 将会员信息存在Session中
				session.setAttribute(SessionConstant.CURRENT_MEMBER, memberDb);
				
				// 登录后，将用户角色放在session中
				MemberUserRole memberUserRole = memberUserRoleService.getMemberUserRoleByUserId(memberDb.getId());
				if(memberUserRole != null){
					MemberRole memberRole = memberRoleService.getMemberRoleById(memberUserRole.getMemberRoleId());
					session.setAttribute("memberRole", memberRole);
				}
				
				String redirectUrl = (String)session.getAttribute("redirectUrl");
				if(!StringUtils.isEmpty(redirectUrl)){
					session.removeAttribute("redirectUrl");
		            return ajaxJSON(Status.success,redirectUrl);
		        }
				String preUrl = (String)session.getAttribute("preUrl");
				if(!StringUtils.isEmpty(preUrl)){
					session.removeAttribute("preUrl");
					return ajaxJSON(Status.success,preUrl);
				}
				
				return ajaxJSON(Status.success,"success");
			}else{
				return ajaxJSON(Status.error, "用户名或密码不正确");
			}
		}catch(Exception e){
			e.printStackTrace();
			return ajaxJSON(Status.error, "登录异常，请查看系统日志");
		}
	}
	
	/**
	 * 会员登出
	 * @return
	 */
	@RequestMapping(value = "/logout.htm", method = RequestMethod.GET)
	public ModelAndView logout(@ModelAttribute MemberUserForm model, HttpServletRequest request, HttpServletResponse response, HttpSession session){
		ModelAndView view = new ModelAndView();
		//转发到首页
		view.setViewName("redirect:/member/login.htm");

		//删除当前用户登录信息
		session.removeAttribute(SessionConstant.CURRENT_MEMBER);
		
		
		return view;
	}
	
	/** 
	 * ========= 【找回密码】电子邮箱的方式找回密码  ========= 
	 * 
	 */
	
	/**
	 * 忘记密码 - 通过邮件找回
	 * @return 
	 */
	@RequestMapping(value = "/forget_email.htm", method = RequestMethod.GET)
	public ModelAndView forgetByEmail(){
		ModelAndView view = new ModelAndView();
		view.setViewName("/member/login/forget_email");
		return view;
	}
	
	/** 
	 * 	发送密码找回邮件 
	 * 	@throws MessagingException 
	 * 
	 */
	@RequestMapping(value = "/forget_email_send.htm",method={RequestMethod.GET,RequestMethod.POST})
	public ModelAndView sendForgetEmail(@ModelAttribute MemberUserForm model, HttpServletRequest request, HttpServletResponse response, HttpSession session) throws MessagingException{
		try{
			/* ======= 1、验证验证码是否正确 ======= */
			Integer v = model.getV();
			
			if(v != null && v.intValue() == 1){
				// 获取客户端输入的验证码
				String verCode = model.getVerCode();
				// 获取服务器端正确的验证码
				String verCodeSession = (String) session.getAttribute(SessionConstant.JAPTCHACODE);
				if (StringUtils.isBlank(verCode) || !verCode.toLowerCase().equals(verCodeSession.toLowerCase())) {
					// 如果验证码为空，或者验证码不正确
					return ajaxJSON(Status.error, "验证码输入不正确");
				}
			}
			
			// 发送时间
			// 验证发送间隔
			boolean checkSendTime = false;
			Date lastTime = (Date) session.getAttribute("sendTime");
			if (lastTime == null) {
				checkSendTime = true;
			}else{
				Long sendEmailTimeLong = lastTime.getTime();
				Long now = new Date().getTime();
				Long reduceResult = (now - sendEmailTimeLong) / 1000;
				request.setAttribute("reduceResult", reduceResult);
				if (reduceResult >= 60) {
					session.setAttribute("sendTime", new Date());
					session.removeAttribute("sendEmailTime");
					checkSendTime = true;
				}
				
				if(!checkSendTime){
					return ajaxJSON(Status.error, "请于"+(60-reduceResult)+"秒后再次发送邮件");
				}
			}
			
			MemberUser member = memberUserService.getMemberUserByEmail(model.getItem().getEmail());
			if(null == member){
				return ajaxJSON(Status.error, "该邮箱不存在");
			}
			
			// 构造发送邮件的内容
			String serverPort = "";
			if (request.getServerPort() != 80) {
				serverPort = ":" + request.getServerPort();
			}
			String serverName = request.getServerName();
			String basePath = request.getScheme() + "://" + serverName + serverPort +request.getContextPath() + "/";
			StringBuffer activateUrl = new StringBuffer();
			activateUrl.append(basePath);

			// 构造验证码
			String authCode = EncryptUtil.encryptionPw(member.getEmail() + member.getPassword());
			session.setAttribute(member.getEmail(), authCode);

			Date sendDate = new Date();
			activateUrl.append("member/forget_email_edit_pwd.htm?email=" + member.getEmail() + "&code=" + authCode + "&m=" + sendDate.getTime());
			
			Map<String, Object> data = new HashMap<String, Object>();
			data.put("url", activateUrl.toString());
			emailService.sendEmail("2","密码找回", member.getEmail(), data);
			
			session.setAttribute("sendTime" , new Date());
			return ajaxJSON(Status.success);
		}catch(Exception ex){
			
			return ajaxJSON(Status.error,"找回密码失败，请稍后重试");
		}
	}
	
	/**
	 * 重置密码
	 * @return 
	 */
	@RequestMapping(value = "forget_email_edit_pwd",method={RequestMethod.GET,RequestMethod.POST})
	public ModelAndView toForgetEmail(@ModelAttribute MemberUserForm model, HttpServletRequest request, HttpServletResponse response, HttpSession session){
		
		ModelAndView modelAndView = new ModelAndView();
		
		// ===== 验证有效性 BEGIN ======= /
		// 获得用户邮箱
		String email = model.getEmail();
		// 获得code
		String code = model.getCode();
		// 获得发送时间戳
		String m = model.getM();

		if (StringUtils.isBlank(email) || StringUtils.isBlank(code) || StringUtils.isBlank(m)) {
			modelAndView.setViewName("/base/error");
			return modelAndView;
		}

		// 验证30分钟内超时
		Long sendTime = Long.parseLong(m);
		Long reduceResult = new Date().getTime() - sendTime;
		if (((reduceResult / 1000) / 60) > 30 * 60) {
			modelAndView.setViewName("/base/error");
			return modelAndView;
		}

		// 验证会员名是否存在
		MemberUser member = memberUserService.getMemberUserByEmail(email);
		if (null == member) {
			modelAndView.setViewName("/base/error");
			return modelAndView;
		}

		// 验证授权验证码是否正确
		String authCode = EncryptUtil.encryptionPw(member.getEmail() + member.getPassword());
		if (!authCode.equals(code)) {
			modelAndView.setViewName("/base/error");
			return modelAndView;
		}
		
		// ===== 验证有效性 END ======= /

		// 验证通过后，将参数返回至修改密码页面
		Map<String, Object> data = modelAndView.getModel();
		data.put("email", email);
		data.put("code", code);
		modelAndView.setViewName("/member/login/forget_email_edit_pwd");
		return modelAndView;
	}
	
	/**
	 * 重置成功
	 * @return 
	 */
	@RequestMapping(value = "forget_email_do_edit",method={RequestMethod.POST})
	public ModelAndView edit_forget_pwd(@ModelAttribute MemberUserForm model, HttpServletRequest request, HttpServletResponse response, HttpSession session){
		ModelAndView modelAndView = new ModelAndView();
		
		// ===== 验证有效性 BEGIN ======= /
		// 获得用户邮箱
		String email = model.getEmail();
		// 获得code
		String code = model.getCode();

		if (StringUtils.isBlank(email) || StringUtils.isBlank(code)) {
			modelAndView.setViewName("/base/error");
			return modelAndView;
		}

		// 验证会员名是否存在
		MemberUser member = memberUserService.getMemberUserByEmail(email);
		if (null == member) {
			modelAndView.setViewName("/base/error");
			return modelAndView;
		}

		// 验证授权验证码是否正确
		String authCode = EncryptUtil.encryptionPw(member.getEmail() + member.getPassword());
		if (!authCode.equals(code)) {
			modelAndView.setViewName("/base/error");
			return modelAndView;
		}
		
		// ===== 验证有效性 END ======= /
		
		String password = model.getPassword();
		
		// 验证通过后，修改密码
		member.setPassword(password);
		member.setUpdateBy(member.getName());
		member.setUpdateDate(new Date());
		memberUserService.updatePwd(member);

		session.setAttribute(SessionConstant.CURRENT_MEMBER, member);
		
		// 跳转到修改成功的页面
		modelAndView.setViewName("/member/login/forget_email_edit_success");
		
		return modelAndView;
	}
	
	
	/** 
	 * ========= 【找回密码】手机短信验证码的方式找回密码  ========= 
	 * 
	 */
	
	
	/**
	 * 忘记密码 - 通过手机找回
	 * @return 
	 */
	@RequestMapping(value = "/forget_by_mobile.htm", method = RequestMethod.GET)
	public ModelAndView forgetByMobile(){
		ModelAndView view = new ModelAndView();
		view.setViewName("/member/login/forget_by_mobile");
		return view;
	}
	
}